<script setup lang="ts">
import {ref, watch, useAttrs} from 'vue';
import dayjs from 'dayjs';

const attrs = useAttrs();

const props = withDefaults(
  defineProps<{
    value: any;
    regionDays?: number;
    isDateRegion?: boolean;
    dateRegion?: number;
  }>(),
  {
    inputValue: undefined, // 值
    regionDays: 30, // 默认选择区域天数 30天
    dateRegion: 7, // 默认展示 时间区域  7 代表展示默认展示一周
    isDateRegion: false, // 是否开启默认时间区间
  },
);
// const emit = defineEmits<{
//   (e: 'update:value', value: any): void;
// }>();

const emit = defineEmits<{
  'update:value': [value: any];
}>();

const dateRegion = ref<any>(
  props.isDateRegion ? [dayjs(dayjs().subtract(props.dateRegion, 'day')), dayjs(dayjs())] : [],
);

const dates = ref<any>();
const hackValue = ref<any>('');

const disabledDate: any = (current: any) => {
  if (!dates.value || (dates.value as any).length === 0) {
    return current && current > dayjs().endOf('day');
  }
  const tooLate = dates.value[0] && current.diff(dates.value[0], 'days') > props.regionDays;
  const tooEarly = dates.value[1] && dates.value[1].diff(current, 'days') > props.regionDays;
  return tooEarly || tooLate || current > dayjs().endOf('day');
};
const onOpenChange = (open: boolean) => {
  if (open) {
    dates.value = [] as any;
    hackValue.value = [] as any;
    emit('update:value', [] as any);
  } else {
    hackValue.value = undefined;
    // emit('update:value', undefined);
  }
};
const onChange = (val: any) => {
  dateRegion.value = val;
  emit('update:value', val);
  // 获取接口
};

const onCalendarChange = (val: any) => {
  dates.value = val;
};
watch(
  () => props.inputValue,
  (nextState, prevState) => {
    hackValue.value = nextState;
  },
);
</script>

<template>
  <!-- style="width: 240px" -->
  <a-range-picker
    :value="hackValue || dateRegion"
    :disabled-date="disabledDate"
    v-bind="attrs"
    format="DD/MM/YYYY"
    @change="onChange"
    @openChange="onOpenChange"
    @calendarChange="onCalendarChange"
  />
</template>

<style lang="less" scoped></style>
